﻿using System;
using System.Data.Entity;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Quadrant.domain.DB;
using Quadrant.web.Helpers;
using Quadrant.web.Models;

namespace Quadrant.web
{
    public class MvcApplication : BaseMvcApplication
    {
     
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Database.SetInitializer(new CreateDatabaseIfNotExists<ApplicationDbContext>());
            Database.SetInitializer(new CreateDatabaseIfNotExists<QuadrantContext>());
            Log.Info("Application Started");
            //GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("json", "true", "application/json"));
        }

        private void Application_Error(Object sender, EventArgs e)
        {
            var exc = Server.GetLastError(); //obtenir l’exception d’origine
            int httpCode = 500; //code par défaut, le plus général possible
            Log.ErrorException("Global Error",exc);
            if (exc is HttpException || exc.GetBaseException() is HttpException)
            {
                var httpException = exc as HttpException ?? exc.GetBaseException() as HttpException;
           
                if (httpException != null) httpCode = httpException.GetHttpCode();
            }
            if (!Request.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                Request.RequestContext.RouteData.Values.Clear();
                Request.RequestContext.RouteData.Values.Add("controller", "Error");
                Request.RequestContext.RouteData.Values.Add("action", "Index");
                Request.RequestContext.RouteData.Values.Add("id", httpCode);
                var controller = new ErrorController() as IController;
                controller.Execute(Request.RequestContext);
            }
            Server.ClearError();
        }

    }
}
